package com.breaktian.assemble.security.aes;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

/**
 * Created by keke.tian on 2018/4/24.
 */

public class AesUtil {
    // 算法名称
    private static final String KEY_ALGORITHM = "AES";
    // 加解密算法/模式/填充方式
    private static final String algorithmStr = "AES/CBC/PKCS5Padding";


    //初始化向量
    static final byte[] IV = { 0x10, 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x55, 0x50, 0x66, 0x77, 0x68, 0x37, 0x30, 0x38 };

    //16个字节的密钥key
    static byte[] KEY = { 0x13, 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x55, 0x50, 0x66, 0x77, 0x68, 0x37, 0x30, 0x37 };


    public static String encrypt(String content,byte[] key,byte[] iv){
        byte[] encryptByte = encrypt(content.getBytes(), KEY, IV);
        return parseByte2HexStr(encryptByte);
    }

    public static String decrypt(String content,byte[] key,byte[] iv){
        byte[] decryptByte = parseHexStr2Byte(content);
        byte[] decrypt = decrypt(decryptByte, key, iv);
        return new String(decrypt);
    }


    public static byte[] encrypt(byte[] content, byte[] keyBytes, byte[] iv){
        try{
            KeyGenerator keyGenerator=KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, new SecureRandom(keyBytes));
            SecretKey key=keyGenerator.generateKey();
            Cipher cipher=Cipher.getInstance(algorithmStr);
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
            byte[] result=cipher.doFinal(content);
            return result;
        }catch (Exception e) {
            System.out.println("exception:"+e.toString());
        }
        return null;
    }

    public static byte[] decrypt(byte[] content, byte[] keyBytes, byte[] iv){
        try{
            KeyGenerator keyGenerator=KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, new SecureRandom(keyBytes));//key长可设为128，192，256位，这里只能设为128
            SecretKey key=keyGenerator.generateKey();
            Cipher cipher=Cipher.getInstance(algorithmStr);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            byte[] result=cipher.doFinal(content);
            return result;
        }catch (Exception e) {
            System.out.println("exception:"+e.toString());
        }
        return null;
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        String test = "我的祖瑶瑶我的祖瑶瑶我的祖瑶瑶我的祖瑶瑶我的祖瑶瑶我的祖瑶瑶321321fsda";
        String encryptStr = encrypt(test, KEY, IV);
        System.out.println("encryptStr:"+encryptStr);
        System.out.println("decryptStr:"+decrypt(encryptStr,KEY,IV));

    }

}
